package track2.data;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

import track2.context.Config;

public class TitleToken {
	static AmazonS3 s3;
	private static TitleToken _instance = null;
	private Map<Integer, String> map = null;
	
	public TitleToken() throws IOException{
		map = new HashMap<Integer, String>();
		_init();
	}
	
	/**
	 * initial map based on the file
	 * @throws IOException 
	 */
	private void _init() throws IOException{
		AWSCredentials credentials = new PropertiesCredentials(
				TitleToken.class.getResourceAsStream("AwsCredentials.properties"));
		s3 = new AmazonS3Client(credentials);
		System.out.println("Loading Title Token begin...");
		try{
			S3Object object = s3.getObject(new GetObjectRequest("bigmlplj",
					"track2/titleid_tokensid.txt"));
			BufferedReader br = new BufferedReader(new InputStreamReader(
					object.getObjectContent()));
//			BufferedReader br = new BufferedReader(new FileReader(Config.titleTokenPath));
			String line;
			while ((line = br.readLine()) != null){
				String[] paras = line.split("\t");//id	seg1|seg2|seg3....
				map.put(Integer.parseInt(paras[0]), paras[1]);
			}
			br.close();
			System.out.println("Loading Title Token finished...");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static synchronized TitleToken getInstance() throws IOException{
		if (_instance == null){
			_instance = new TitleToken();
		}
		return _instance;
	}
	
	public Map<Integer, String> getMap() {
		return map;
	}

}
